package spindles.gwt.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.GWT.UncaughtExceptionHandler;

public class ErrorHandler {
	
	private ErrorHandler(){}
	
	public static void initErrorHandling() {        
        GWT.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
            public void onUncaughtException(final Throwable tracepoint) {
                showErrorDialog(tracepoint);
            }
        });
    }
	
	public static void showErrorDialog(final Throwable caught) {
        if (caught != null) {
            showErrorDialog(caught.getMessage());
            caught.printStackTrace();
        } else {
            final String message = "Unexpected error. Contact administrator...";
            showErrorDialog(message);
        }
    }
	
	public static void showErrorDialog(String content){
		InfoDialog dlg = new InfoDialog("Error(s) occurred!", content);
		dlg.show();
		dlg.center();
	}
	
	public static String[] getStacktraceAsString(final Throwable tracepoint) {
        final StackTraceElement[] trace = tracepoint.getStackTrace();
        final StringBuffer sbuf = new StringBuffer(2048);
        sbuf.append(tracepoint.toString());
        sbuf.append(": at\n");
        // Cut the stacktrace at depth 7
        final int length = Math.min(7, trace.length);
        for (int i = 0; i <= length; i++) {
            sbuf.append(trace[i].toString());
            sbuf.append("\n");
        }
        if (trace.length > 7) {
            sbuf.append("...");
        }
        final String stacktrace = sbuf.toString();
        return new String[]{tracepoint.getMessage(), stacktrace};
    }
	
	public static String getStackTrace(Throwable e){
		StringBuffer result = new StringBuffer(); 
		for(int i = 0; i < e.getStackTrace().length; i++){
			result.append(e.getStackTrace()[i].toString());
		}
		
		return result.toString();
	}
	
	

}
